import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

// 获取或创建用户
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { id, name, email, avatar } = body

    if (!id || !name || !email) {
      return NextResponse.json({ error: 'ID, name and email are required' }, { status: 400 })
    }

    // 尝试查找现有用户
    let user = await prisma.user.findUnique({
      where: { id }
    })

    // 如果用户不存在，创建新用户
    if (!user) {
      user = await prisma.user.create({
        data: {
          id,
          name,
          email,
          password: 'default_password', // 临时默认密码，实际应用中应该生成随机密码
          avatar
        }
      })
    }

    return NextResponse.json({ user })
  } catch (error) {
    console.error('Error creating/finding user:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

// 获取用户信息
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')

    if (!userId) {
      return NextResponse.json({ error: 'User ID is required' }, { status: 400 })
    }

    const user = await prisma.user.findUnique({
      where: { id: userId }
    })

    if (!user) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 })
    }

    return NextResponse.json({ user })
  } catch (error) {
    console.error('Error fetching user:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}
